package com.rtx.express.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.CainiaoWaybillIiGetRequest;
import com.taobao.api.response.CainiaoWaybillIiGetResponse;

import cn.hutool.core.util.IdUtil;

@RtxExpressApi(expressApiName = "淘系-TOP-菜鸟")
@Service("快递接口TM")
public class TMExpressAPI implements IExpressService{
	Logger log = LoggerFactory.getLogger(this.getClass());

	private String url ="http://gw.api.taobao.com/router/rest";
	private String vendorId ="327354334";
//	private String accesstoken ="61007019e11a618eaf1d633be2d321767a8415c61f641ae2213450139267";
	private String appkey ="28428678";
	private String appSecret ="e398a1b5ffdd176041306916f18d820d";
	
	
	/**
	 * 获取快递单号
	 * @param parameter
	 * @return
	 * @throws Exception
	 */
	private CainiaoWaybillIiGetResponse getExpress(ExpressBO bo) throws Exception{
//		PlExpressApiConfig config = bo.getExpressConfig();
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, appSecret);
		CainiaoWaybillIiGetRequest req = mappingToRequest(bo);
		log.info("菜鸟平台获取快递单号请求报文："+ JSON.toJSONString(req));
		CainiaoWaybillIiGetResponse rsp = client.execute(req, bo.getExpressConfig().getAccessToken());
		log.info("菜鸟平台获取快递单号返回报文："+ JSON.toJSONString(rsp));
		return rsp;
	}
	
	/**
	 * 在线文档
	 * https://open.taobao.com/doc.htm?docId=26869&docType=2#s20
	 * 设置请求数据
	 * @param parameter
	 * @return
	 * @throws Exception
	 */
	private CainiaoWaybillIiGetRequest mappingToRequest(ExpressBO bo) throws Exception{
		PlExpressApi task =  bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		
		CainiaoWaybillIiGetRequest req = new CainiaoWaybillIiGetRequest();
		CainiaoWaybillIiGetRequest.WaybillCloudPrintApplyNewRequest obj1 = new CainiaoWaybillIiGetRequest.WaybillCloudPrintApplyNewRequest();
		obj1.setCpCode(task.getPlatformCarriercode());//物流公司
		obj1.setBrandCode(task.getBrandcode());
		CainiaoWaybillIiGetRequest.UserInfoDto obj2 = new CainiaoWaybillIiGetRequest.UserInfoDto();
		CainiaoWaybillIiGetRequest.AddressDto obj3 = new CainiaoWaybillIiGetRequest.AddressDto();
		obj1.setProductCode(task.getProductCode());
//		CainiaoWaybillIiSearchResponse.AddressDto addressDto= getSendAddress(task.getCarrierCode(),task);//获取发货地址
		
		obj3.setDetail(task.getSendAddress());//发货地址
		obj3.setDistrict(task.getSendCounty());//发货区县
		obj3.setProvince(task.getSendProvince());//发货省份
		obj3.setTown(task.getSendTown());//发货街道
		obj3.setCity(task.getSendCity());//发货城市
		obj2.setAddress(obj3);
		
		obj2.setMobile(task.getSendMobile());//发货人手机
		obj2.setName(task.getSendName());//发货人姓名
		obj2.setPhone(task.getSendPhone());//发货人固话
		obj1.setSender(obj2);
		
		
		List<CainiaoWaybillIiGetRequest.TradeOrderInfoDto> list5 = new ArrayList<CainiaoWaybillIiGetRequest.TradeOrderInfoDto>();
		CainiaoWaybillIiGetRequest.TradeOrderInfoDto obj6 = new CainiaoWaybillIiGetRequest.TradeOrderInfoDto();
		//obj6.setLogisticsServices("");
		if(bo.getZdflag()==true) {
			obj6.setObjectId(task.getExternorderkey()+System.currentTimeMillis());//请求ID
		}else {
			obj6.setObjectId(task.getExternorderkey());//请求ID
		}
		
		CainiaoWaybillIiGetRequest.OrderInfoDto obj8 = new CainiaoWaybillIiGetRequest.OrderInfoDto();
//		obj8.setOrderChannelsType("TB");//订单渠道平台编码
		obj8.setOrderChannelsType(config.getChannelsType());//订单渠道平台编码
		if(bo.getZdflag()==true) {
			obj8.setTradeOrderList(Collections.singletonList(IdUtil.getSnowflakeNextIdStr()));//订单号
		}else {
			obj8.setTradeOrderList(Collections.singletonList(task.getExternorderkey()));//订单号
		}

		
		obj6.setOrderInfo(obj8);
		list5.add(obj6);
		CainiaoWaybillIiGetRequest.PackageInfoDto obj10 = new CainiaoWaybillIiGetRequest.PackageInfoDto();
		List<CainiaoWaybillIiGetRequest.Item> list12 = new ArrayList<CainiaoWaybillIiGetRequest.Item>();
		CainiaoWaybillIiGetRequest.Item obj13 = new CainiaoWaybillIiGetRequest.Item();
		obj13.setCount(1L);//商品数量
		obj13.setName("衣服");//商品名称
		list12.add(obj13);
		obj10.setItems(list12);
		obj10.setGoodsDescription("服装");
		obj6.setPackageInfo(obj10);
		CainiaoWaybillIiGetRequest.RecipientInfoDto obj15 = new CainiaoWaybillIiGetRequest.RecipientInfoDto();
		CainiaoWaybillIiGetRequest.AddressDto obj16 = new CainiaoWaybillIiGetRequest.AddressDto();
		obj16.setCity(task.getReceiverCity());//收件人城市
		obj16.setDetail(task.getReceiverAddress());//收件人详细地址
		obj16.setDistrict(task.getReceiverCounty());//收件人区县
		obj16.setProvince(task.getReceiverProvince());//收件人省份
		obj15.setAddress(obj16);
		obj15.setMobile(task.getReceiverMobile());//收件人手机
		obj15.setName(task.getReceiverName());//收件人姓名
		obj15.setPhone(task.getReceiverPhone());//收件人固话
		if(!"DW".equals(config.getRtxsalesp())) {
			obj15.setTid(task.getTid());
		}
		if("1688".equals(config.getRtxsalesp())) {
			obj15.setCaid(task.getOaid());
		}else {
			obj15.setOaid(task.getOaid());
		}
		obj6.setRecipient(obj15);
//		obj6.setTemplateUrl(getTempleUrl(parameter.getCarriercode()));//云打印标准模板URL
		obj6.setTemplateUrl(config.getTemplatesurl());//云打印标准模板URL
		obj6.setUserId(Long.parseLong(vendorId));//使用者ID
		obj1.setTradeOrderInfoDtos(list5);
		req.setParamWaybillCloudPrintApplyNewRequest(obj1);
		return req;
	}

	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
		try {
			//映射token
			mappingConfig(bo);
			
			//获取单号&打印报文
			CainiaoWaybillIiGetResponse rsp = getExpress(bo);
			
			
			List<CainiaoWaybillIiGetResponse.WaybillCloudPrintResponse> responseList =	rsp.getModules();
			if(responseList != null && responseList.size()>0){
				bo.setCallCreateOrderAPIResult("ok");
				bo.setCallCreateOrderAPIData(responseList.get(0).getPrintData());
				
				PlExpressResult result = new PlExpressResult();
				result.setResponseStr(bo.getCallCreateOrderAPIData());
				result.setExternorderkey(task.getExternorderkey());
				result.setWaybillNo(responseList.get(0).getWaybillCode());
				result.setPrintData(responseList.get(0).getPrintData());
				
				bo.setExpressResult(result);
			}else {
				bo.setMsg("订单-"+task.getExternorderkey()+"-获取菜鸟快递单号失败：" + JSON.toJSONString(rsp));
			}
		} catch (Exception e) {
			log.error("订单-"+task.getExternorderkey()+"-获取菜鸟快递单号失败：" + e.getMessage());
			bo.setMsg("订单-"+task.getExternorderkey()+"-获取菜鸟快递单号失败：" + e.getMessage());
		}
		
	}
	
	private void mappingConfig(ExpressBO bo) {
		PlExpressApiConfig config =	bo.getExpressConfig();
		if(!StringUtils.hasLength(config.getAccessToken())) {
			config.setAccessToken("61007019e11a618eaf1d633be2d321767a8415c61f641ae2213450139267");
		}
	}

	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {}
}
